import os

from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
from django.dispatch import receiver
from django.template.defaultfilters import slugify
from django.utils.timezone import now

from ..utils import uuid


class Profile(models.Model):
    """
    扩展用户模型
    """

    user = models.OneToOneField(
        User,
        primary_key=True,
    )
    birthday = models.DateField(
        blank=True,
        null=True,
        help_text="生日(YYYY-MM-DD格式，用来显示年龄)",
    )
    location = models.CharField(
        max_length=40,
        blank=True,
        help_text="家庭住址",
    )
    website = models.URLField(
        blank=True,
        help_text="个人博客或网站",
    )
    bio = models.TextField(
        blank=True,
        help_text="个人简介",
    )

    def get_avatar(self):
        no_avatar = settings.STATIC_URL + 'img/no_avatar.jpg'
        filename = settings.MEDIA_ROOT + '/avatars/{year}/{month}/{day}/'.format(
            year = self.user.date_joined.year,
            month = self.user.date_joined.month,
            day = self.user.date_joined.day) + self.user.username + '.jpg'
        avatar_url = settings.MEDIA_URL + 'avatars/{year}/{month}/{day}/'.format(
            year = self.user.date_joined.year,
            month = self.user.date_joined.month,
            day = self.user.date_joined.day) + self.user.username + '.jpg'
        if os.path.isfile(filename):
            return avatar_url
        else:
            return no_avatar

    def age(self):
        """
        计算用户的年龄
        """
        if not self.birthday:
            return None
        n, b = now().date(), self.birthday
        return n.year - b.year - (0 if n.month > b.month or n.month == b.month and n.day >= b.day else 1)

    @models.permalink
    def get_absolute_url(self):
        kwargs, slug = {'id': self.user.id}, slugify(self)
        if slug:
            kwargs['slug'] = slug
        return ('accounts:profile', (), kwargs)

    def __str__(self):
        return self.user.get_full_name() or self.user.get_username()

    class Meta:
        ordering = ('-user__last_login',)


@receiver(models.signals.post_save, sender=User)
def create_profile(instance, created, **kwargs):
    """
    当新用户被创建同时为其创建扩展
    """
    if created:
        Profile.objects.create(user=instance)


class ConfirmationKey(models.Model):
    """
    确认令牌用于帐号认证和密码重置
    """

    user = models.OneToOneField(User, primary_key=True)
    key = models.CharField(max_length=32, default=uuid)

    def __str__(self):
        return self.user
